<script lang="ts">
import { debounce } from '@peng_kai/kit/libs/lodash-es';
import { useEventListener } from '@peng_kai/kit/libs/vueuse';
import GameLoading from './GameLoading.vue';
import { useLoadGameElement } from './helpers';

function markCurrencyRefreshEmitedGame() {
  let is = false;
  let timer = -1;

  const mark = () => {
    is = true;
    clearTimeout(timer);
    timer = setTimeout(() => is = false, 1000);
  };

  const clear = () => {
    is = false;
    clearTimeout(timer);
  };

  return {
    get is() {
      return is;
    },
    mark,
    clear,
  };
}
</script>

<script setup lang="ts">
const props = defineProps<{
  gameCode: string;
  isDev?: boolean;
}>();

const appStore = useAppStore();
const currencyStore = useCurrencyStore();
const appSocket = useAppSocket();
const gameCode = toRef(props, 'gameCode');
const { GameElement, gameElementRef, displayLoading, gameElementPresetProps } = useLoadGameElement(gameCode, 'play');
const currencyRefreshEmitedGame = markCurrencyRefreshEmitedGame();

function refreshGameBalance() {
  gameElementRef.value?.refreshBalance?.();
}

function refeshHostBalance(currency?: string) {
  const finalCurrency = currency || currencyStore.cryptoName;

  if (finalCurrency) {
    appSocket.send('USER_BALANCE_REQ', 'BalanceResp', (data) => {
      data.Currency = finalCurrency;
      return data;
    });
  }
}

watch(() => currencyStore.crypto, (newCrypto, oldCrypto) => {
  if (!newCrypto || !oldCrypto)
    return;

  if (currencyRefreshEmitedGame.is) {
    currencyRefreshEmitedGame.clear();
    return;
  }

  refreshGameBalance();
}, { deep: true, immediate: true });

useEventListener(gameElementRef, 'login', () => globalPopups.sign.open());
useEventListener(gameElementRef, 'deposit', () => globalPopups.wallet.open());
useEventListener(gameElementRef, 'refresh', () => location.reload()); // TODO:暂时方案，最好使用路由刷新
useEventListener(gameElementRef, 'openGameRecord', (ev: any) => globalPopups.gameRecordDetail.open(ev.detail[0]));
useEventListener(gameElementRef, 'updateGameState', (ev: any) => {
  const state = ev.detail[0].state;
  appStore.hiddenBalanceReason = state === 'playing' ? 'Playing...' : '';
  state === 'idle' && refeshHostBalance();
});
useEventListener(gameElementRef, 'addMyLog', debounce((ev: any) => {
  const currency = ev.detail[0]?.currency;

  if (!currency)
    return;

  currencyRefreshEmitedGame.mark();

  // 暂时基于 addMyLog 事件做的余额请求,
  // 因为收到 addMyLog 事件时代表游戏以出结果（包含动画时间）
  refeshHostBalance(currency);
}, 50, { maxWait: 500, leading: true, trailing: false }));
</script>

<template>
  <div class="relative min-h-130">
    <component
      :is="GameElement"
      v-if="GameElement"
      v-bind="gameElementPresetProps"
      :class="{ invisible: displayLoading }"
      :currency="currencyStore.cryptoName"
    />
    <GameLoading v-if="displayLoading" />
  </div>
</template>
